package com.huowei.htzy.application;


import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

/**
 * Created by huowei on 2016/10/10.
 */

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
    }
    /**
     * 检查当前网络是否可用
     *
     * @return
     */

    public static boolean isNetworkAvailable(Activity activity)
    {
        Context context = activity.getApplicationContext();
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null)
        {
            return false;
        }
        else
        {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0)
            {
                for (int i = 0; i < networkInfo.length; i++)
                {
                    System.out.println(i + "===状态===" + networkInfo[i].getState());
                    System.out.println(i + "===类型===" + networkInfo[i].getTypeName());
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 检测当前的网络连接是否可用<br/>
     * 注意：需要添加权限&lt;uses-permission
     * android:name="android.permission.ACCESS_NETWORK_STATE"/&gt;
     *
     * @param context
     * @return
     */
    public static boolean isConnected(Context context) {
        boolean flag = false;
        try {
            ConnectivityManager connManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (null != connManager) {
                NetworkInfo info = connManager.getActiveNetworkInfo();
                if (null != info && info.isAvailable()) {
                    flag = true;
                }
            }
        } catch (Exception e) {
            Log.e("NetworkInfo", "Exception", e);
        }
        return flag;
    }

}
